package com.xxg.renrenlogin.util;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;


/**
 * Rest服务调用工具
 *
 * @author xxg
 * @date 2020-09-25
 */
@Component
public class RestServiceUtil {

    private static final RestTemplate REST_TEMPLATE = new RestTemplate();

    public RestServiceUtil() {
        REST_TEMPLATE.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
    }

    /**
     * POST方式调用外部系统的服务接口
     *
     * @param serviceUrl  服务接口地址
     * @param requestArgs 接口参数
     * @param header      返回参数类型
     * @param clazz       返回参数类型
     * @param <T>         泛型
     * @return 结果
     * @throws Exception 异常信息
     */
    public static <T> T remotePostCall(String serviceUrl, Object requestArgs, String header, Class<T> clazz) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", header);
        HttpEntity request = new HttpEntity(requestArgs, headers);
        REST_TEMPLATE.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        ResponseEntity<T> responseEntity = REST_TEMPLATE.postForEntity(serviceUrl, request, clazz);
        return responseEntity.getBody();
    }

    /**
     * GET方式调用外部系统的服务接口
     *
     * @param serviceUrl 服务接口地址
     * @param clazz      返回参数类型
     * @param <T>        泛型
     * @return 结果
     * @throws Exception 异常信息
     */
    public static <T> T remoteGetCall(String serviceUrl, Class<T> clazz) throws Exception {
        ResponseEntity<T> responseEntity = REST_TEMPLATE.getForEntity(serviceUrl, clazz);
        return responseEntity.getBody();
    }
}
